package com.mowanka.mokeng.app.network

import android.os.Build
import com.mowanka.mokeng.BuildConfig
import com.mowanka.mokeng.app.util.CacheUtil
import com.mowanka.mokeng.app.util.SignUtil
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {

    private val endStr = "344B5973547079545777"

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
//        val builder = chain.request().newBuilder()
//
//        CacheUtil.getUser()?.token?.let {
//            builder.addHeader("token", it)
//        }
//        return chain.proceed(builder.build())


        val original = chain.request()
        val map: MutableMap<String, String?> = HashMap()
        if ("GET" == original.method) {
            val urlBuilder = original.url.newBuilder()
            val httpUrl = urlBuilder.build()
            // 打印所有get参数
            val paramKeys = httpUrl.queryParameterNames
            for (key in paramKeys) {
                map[key] = httpUrl.queryParameter(key)
            }
        } else if ("POST" == original.method) { // POST方法
            // FormBody和url不太一样，若需添加公共参数，需要新建一个构造器
            val bodyBuilder = FormBody.Builder()
            // 把已有的post参数添加到新的构造器
            if (original.body is FormBody) {
                val formBody = original.body as FormBody
                for (i in 0 until formBody.size) {
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
                }
            }
            // 这里可以添加一些公共post参数
            val newBody = bodyBuilder.build()
            for (i in 0 until newBody.size) {
                map[newBody.name(i)] = newBody.value(i)
            }
        }
        val timeStamp = (System.currentTimeMillis() / 1000).toString()
        map["appid"] = "mk20190513"
        map["appSecret"] = (SignUtil.xor("3I!gt", "x\$RU9") + SignUtil.sqrt(4802)[0]
                + "uvC9Jki5pRvTGB" + SignUtil.hexStr2Str(endStr))
        map["timeStamp"] = timeStamp

        val request = original.newBuilder().apply {
            method(original.method, original.body)
            addHeader("appid", "mk20190513")
            addHeader("timeStamp", timeStamp)
            addHeader("sign", SignUtil.getMapSign(map))
            CacheUtil.getUser()?.let {
                addHeader("token", it.token)
                addHeader("userId", it.id)
            }

            addHeader("ver", BuildConfig.VERSION_NAME)
            addHeader("verCode", BuildConfig.VERSION_CODE.toString())
            addHeader("os", "0")
            addHeader("osver", Build.VERSION.SDK_INT.toString())
            addHeader("phone", "${Build.BRAND} ${Build.MODEL}")
            addHeader("Connection", "close")

//            addHeader(
//                "netWork", when (netType) {
//                    1 -> "WIFI"
//                    2 -> "2G"
//                    3 -> "3G"
//                    4 -> "4G"
//                    5 -> "5G"
//                    else -> "None"
//                }
//            )
//            oaid?.let { addHeader("oaid", it) }
//            imeiString?.let { addHeader("imei", it) }
//            androidID?.let { addHeader("androidId", it) }
//            addHeader("iden", TVCUtils.getDevUUID(mContext))
//            if (channelString == null) channelString = CommonUtils.getChannel(mContext)
//            addHeader("channel", channelString ?: "mokeng")
//            DataHelper.getStringSF(mContext, Constants.SpKey.Backup_UserId)?.let {
//                addHeader("userIdBackup", it)
//            }
        }.build()

        return chain.proceed(request)
    }

}